/*
 * Chastoslov
 * Copyright (C) 2009 Alexandr Stroghov
 * 
 * stroghov@gmail.com
 * 
 * This program is free software; you can redistribute it and/or modify it under the terms of the 
 * GNU General Public License, version 2, as published by the Free Software Foundation.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; 
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * See the GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program; if 
 * not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, 
 * MA 02111-1307 USA
*/
package world.ah.wf.guiclient;
import java.awt.Frame;
import java.awt.Dimension;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Types;
import java.util.Properties;
import javax.swing.ImageIcon;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import java.awt.Rectangle;
import java.awt.BorderLayout;
import javax.swing.JButton;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ComponentEvent;
import java.awt.event.WindowEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.TableColumnModel;
import java.awt.event.FocusEvent;
import java.awt.event.MouseEvent;
import java.awt.event.KeyEvent;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.Insets;

public class DialogTexts extends JDialog {
  private String[] TextListColumns = {"Title", "Note"};
  private Connection conn;
  public void setConn(Connection conn) {this.conn = conn;};
  //
  DBTableModel tmTexts = new DBTableModel(true) {
    public DBPostResult postChanges(int column, Object[] record, Object newValue) {
      return tmTexts_postChanges (column, record, newValue);
    }
    public boolean postDeletion(Object[] record) {
      return tmTexts_postDeletion(record);
    }
  };
  //
  private int[] tableColWidths = {100, 100};
  
  private ImageIcon imageInsert = new ImageIcon(DialogTexts.class.getResource("insertrecord.gif"));
  private ImageIcon imageDelete = new ImageIcon(DialogTexts.class.getResource("deleterecord.gif"));
  private ImageIcon imageRefresh = new ImageIcon(DialogTexts.class.getResource("refresh.gif"));
  private BorderLayout borderLayout1 = new BorderLayout();
  private JButton bInsert = new JButton();
  private JScrollPane spTable = new JScrollPane();
  private JTable tTexts = new JTable();
  private JPanel pButtons = new JPanel();
  private JButton bClose1 = new JButton();
  private JButton bRefresh = new JButton();
  private JButton bDelete = new JButton();
  private GridBagLayout layoutButtons = new GridBagLayout();



  public DialogTexts() {this(null, "", false);}
  //
  public DialogTexts(Frame parent, String title, boolean modal) {
    super(parent, title, modal);
    try {jbInit();} catch(Exception e) {e.printStackTrace();}
    // МОЯ ИНИЦИАЛИЗАЦИЯ 
    General.centerFrame(this);
    //
    tTexts.getTableHeader().setReorderingAllowed(false);
    // Load form properties
    Properties prop = new Properties();
    try {
      prop.load (new FileInputStream("wfDialogTexts.properties"));
    } catch(Exception ex) {
      ErrorShower.show(null, "loading the DialogTexts properties", "", ex);
    }
    Rectangle rect = new Rectangle();
    try {rect.x = Integer.parseInt(prop.getProperty("Left"));}
    catch (Exception ex) {rect.x = 100;}
    try {rect.y = Integer.parseInt(prop.getProperty("Top"));}
    catch (Exception ex) {rect.y = 200;}
    try {rect.width = Integer.parseInt(prop.getProperty("Width"));}
    catch (Exception ex) {rect.width = 350;}
    try {rect.height = Integer.parseInt(prop.getProperty("Height"));}
    catch (Exception ex) {rect.height = 200;}
    this.setBounds(rect);
    TableColumnModel cols = tTexts.getTableHeader().getColumnModel();
    for(int i = 0; i < tableColWidths.length; i++)
      try {tableColWidths[i] = Integer.parseInt(prop.getProperty("TabColWidth" + 
        Integer.toString(i)));}
      catch (Exception ex) {}
    // загрузили
    // Язык
    setLang();
    //
    DBField[] dBFields = {
      new DBField("TITLE", TextListColumns[0], String.class, false),
      new DBField("NOTE", TextListColumns[1], String.class, false)
    };
    tmTexts.setDBFields(dBFields);
    tTexts.setModel(tmTexts);
    //
    tTexts.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
      public void valueChanged(ListSelectionEvent ev) {
        tTexts_valueChanged(ev);
      }
    });
  }
  //
  private void jbInit() throws Exception {
    this.setSize(new Dimension(320, 200));
    this.getContentPane().setLayout(borderLayout1);
    this.setTitle("Texts");
    this.setModal(true);
    this.addWindowListener(new java.awt.event.WindowAdapter()
      {
        public void windowClosing(WindowEvent e)
        {
          this_windowClosing(e);
        }
      });
    this.addComponentListener(new java.awt.event.ComponentAdapter()
      {
        public void componentShown(ComponentEvent e)
        {
          this_componentShown(e);
        }

        public void componentResized(ComponentEvent e)
        {
          this_componentResized(e);
        }

        public void componentHidden(ComponentEvent e)
        {
          this_componentHidden(e);
        }
      });
    bInsert.setIcon(imageInsert);
    bInsert.setMargin(new Insets(2, 2, 2, 2));
    bInsert.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          bInsert_actionPerformed(e);
        }
      });
    spTable.addKeyListener(new java.awt.event.KeyAdapter()
      {
        public void keyTyped(KeyEvent e)
        {
          spTable_keyTyped(e);
        }
      });
    spTable.addMouseListener(new java.awt.event.MouseAdapter()
      {
        public void mouseClicked(MouseEvent e)
        {
          spTable_mouseClicked(e);
        }
      });
    spTable.addFocusListener(new java.awt.event.FocusAdapter()
      {
        public void focusGained(FocusEvent e)
        {
          spTable_focusGained(e);
        }
      });
    pButtons.setLayout(layoutButtons);
    bClose1.setText("Close");
    bClose1.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          bClose_actionPerformed(e);
        }
      });
    bRefresh.setIcon(imageRefresh);
    bRefresh.setMargin(new Insets(2, 2, 2, 2));
    bRefresh.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          bRefresh_actionPerformed(e);
        }
      });
    bDelete.setIcon(imageDelete);
    bDelete.setMargin(new Insets(2, 2, 2, 2));
    bDelete.addActionListener(new ActionListener()
      {
        public void actionPerformed(ActionEvent e)
        {
          bDelete_actionPerformed(e);
        }
      });
    pButtons.add(bInsert, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 5), 0, 0));
    pButtons.add(bDelete, new GridBagConstraints(1, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 5, 10, 5), 0, 0));
    pButtons.add(bRefresh, new GridBagConstraints(2, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 5, 10, 10), 0, 0));
    pButtons.add(bClose1, new GridBagConstraints(3, 0, 1, 1, 1.0, 0.0, GridBagConstraints.EAST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0));
    this.getContentPane().add(pButtons, BorderLayout.SOUTH);
    spTable.getViewport().add(tTexts, null);
    this.getContentPane().add(spTable, BorderLayout.CENTER);
  }

  private void bClose_actionPerformed(ActionEvent e) {
    this.setVisible(false);
  }

  private void this_componentShown(ComponentEvent e) {
    bRefresh_actionPerformed(null);
    tTexts_valueChanged(null);
  }
  
  private DBPostResult tmTexts_postChanges(int column, Object [] record, Object newValue) {
    DBPostResult result = new DBPostResult(false, null);
    try {
      CallableStatement st = conn.prepareCall("{call UPSERT_TEXT(?, ?, ?, ?, ?)}");
      st.registerOutParameter(2, Types.VARCHAR);
      st.registerOutParameter(3, Types.INTEGER);
      st.registerOutParameter(4, Types.VARCHAR);
      st.registerOutParameter(5, Types.VARCHAR);
      if(record[0] == null) {st.setString(1, "I"); st.setInt(3, -1);}
      else {st.setString(1, "U"); st.setObject(3, record[0]);}
      for(int i = 1; i < record.length; i++) {
        Object ob = i == column + 1 ? newValue : record[i];
        if(ob == null) st.setString(i + 3, "");
        else st.setString(i + 3, (String)ob);
      }
      st.executeUpdate();
      if(st.getString(2).equalsIgnoreCase("Y")) {
        Object[] NewRecord = new Object[record.length];
        for(int i = 0; i < NewRecord.length; i++)
          NewRecord[i] = st.getObject(i + 3);
        result.setNewRecord(NewRecord);
      }
      result.setSucceed(true);
    } catch (Exception ex) {
      ErrorShower.show(this, "posting data", "", ex);
      result.setSucceed(false);
    }
    return result;
  }
  
  private boolean tmTexts_postDeletion(Object [] record) {
    
    //System.out.println("DELETE");
    
    if(record[0] == null) return true;
    else 
      try {
        String sql = "delete from TEXT where ID = ?";
        PreparedStatement st = conn.prepareStatement(sql);
          st.setInt(1, ((Integer)record[0]).intValue());
          st.executeUpdate();
          return true;
      } catch (Exception ex) {
        ErrorShower.show(this, "posting data", "", ex);
        return false;
      }
  }

  private void this_componentResized(ComponentEvent e) {
    General.controlMinimumSize(this, 320, 200);
  }

  private void bRefresh_actionPerformed(ActionEvent e) {
    TableColumnModel cols = tTexts.getTableHeader().getColumnModel();
    if(cols != null) 
      for(int i = 0; i < cols.getColumnCount(); i++) 
        tableColWidths[i] = cols.getColumn(i).getWidth();
    try {
      Statement st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, 
        ResultSet.CONCUR_READ_ONLY, ResultSet.CLOSE_CURSORS_AT_COMMIT);
      ResultSet rs = st.executeQuery("select ID, TITLE, NOTE from TEXT order by 2 asc");
      tmTexts.setDataSource(rs);
      rs.close();
    } catch(Exception ex) {
      ErrorShower.show(this, "fill text list", "", ex);
    }
    cols = tTexts.getTableHeader().getColumnModel();
    for(int i = 0; i < cols.getColumnCount(); i++) 
      cols.getColumn(i).setPreferredWidth(tableColWidths[i]);
      
      //cols.getColumn(i).setModelIndex(1);
      
  }

  private void this_windowClosing(WindowEvent e) {
    //System.out.println("windowClosing");
  }

  private void this_componentHidden(ComponentEvent e) {
  
    //System.out.println("componentHidden: " + this.getBounds().toString());
  
    // Save form properties
    Properties prop = new Properties();
    prop.setProperty("Left", Integer.toString(this.getBounds().x));
    prop.setProperty("Top", Integer.toString(this.getBounds().y));
    prop.setProperty("Width", Integer.toString(this.getBounds().width));
    prop.setProperty("Height", Integer.toString(this.getBounds().height));
    //
    TableColumnModel cols = tTexts.getTableHeader().getColumnModel();
    for(int i = 0; i < cols.getColumnCount(); i++)
      prop.setProperty("TabColWidth" + Integer.toString(i), 
        Integer.toString(cols.getColumn(i).getWidth()));
    try {
      prop.store(new FileOutputStream("wfDialogTexts.properties"), "DialogTexts parameters");
    } catch (Exception ex) {
      ErrorShower.show(this, "saving the DialogTexts properties", "", ex);
    }  
  }

  private void bInsert_actionPerformed(ActionEvent e) {
    tmTexts.insert();
  
  
  }

  private void bDelete_actionPerformed(ActionEvent e) {
    int selected = tTexts.getSelectedRow();
    if(selected >= 0) {
      int confirmResult = JOptionPane.showConfirmDialog(this, 
        General.getLangItem("sureToDeleteTextQuest", "Do you really want to delete this text?"),
        General.getLangItem("Question", "Question"), JOptionPane.YES_NO_OPTION); 
      if(confirmResult == JOptionPane.YES_OPTION) tmTexts.delete(tTexts.getSelectedRow());
    }
  }

  private void spTable_focusGained(FocusEvent e) {
    //System.out.println(e.paramString());
  }

  private void spTable_mouseClicked(MouseEvent e) {
    //System.out.println(e.paramString());
  }

  private void spTable_keyTyped(KeyEvent e) {
    //System.out.println(e.paramString());
  }

  private void tTexts_valueChanged(ListSelectionEvent ev) {
    bDelete.setEnabled(tTexts.getSelectedRow() >= 0);
  }

  /** Устанавливает язык интерфейса */
  public void setLang() {
    String s;
    s = General.getLangItem("Texts"); if(s.length() > 0) this.setTitle(s);
    s = General.getLangItem("Title"); if(s.length() > 0) TextListColumns[0] = s;
    s = General.getLangItem("Note"); if(s.length() > 0) TextListColumns[1] = s;
    s = General.getLangItem("Close"); if(s.length() > 0) bClose1.setText(s);
  }
  // 
  
  
  
}
